/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tbquestion_client.form;

import bllobjects.Account;
import fsktms.request.IRequestDelegate;
import fsktms.request.Request;
import fsktms.request.RequestParameters;
import fsktms.request.RequestRespond;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.ClientModel;
import model.FriendListModel;
import qclient.QClient;

/**
 *
 * @author Mrkupi
 */
public class menu extends javax.swing.JFrame
{
    private FriendListModel userModel = new FriendListModel();
    private ArrayList<Boolean> isFriendList = new ArrayList();
    
    public menu(  ) 
    {
        initComponents();
        
        myInit();
        setLocation( 400, 200 );
    }
    
    private void myInit()
    {
        setResizable(false);
        
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
        
        friendList  =   new javax.swing.JList(this.userModel){
             @Override
             public String getToolTipText(MouseEvent e)
             {
                 int index = locationToIndex(e.getPoint());
                 if (-1 < index) 
                 {
                     return ((Account) this.getModel().getElementAt(index)).getDescription();
                 } 
                 else 
                 {
                     return null;
                 }
             }
        };
        friendList.setLocation(215, 120);
        friendList.setVisible(true);
        friendList.setSize(210, 350);
        friendList.setBorder(BorderFactory.createLineBorder(Color.black));
        friendList.addMouseListener( new MouseAdapter(){
            @Override
            public void mousePressed( MouseEvent e )
            {
            }
            
            @Override
            public void mouseClicked( MouseEvent e )
            {
                if( e.getClickCount() == 2 )
                {
                    int selectedIndex = friendList.getSelectedIndex();
                    if (selectedIndex >= 0)
                    {
                        Account selectedAccount = (Account) userModel.getElementAt(selectedIndex);
                        ClientModel.getInstance().getForms().showChatForm(selectedAccount, ClientForms.CHATFORM_PRIVATE);
                    }
                }
            }
        } );
        this.add(friendList);
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btChatBox = new javax.swing.JButton();
        btGame = new javax.swing.JButton();
        btSearch = new javax.swing.JButton();
        btMessages = new javax.swing.JButton();
        btRequest = new javax.swing.JButton();
        btInfo = new javax.swing.JButton();
        tfSearch = new javax.swing.JTextField();
        btEnter = new javax.swing.JButton();
        add = new javax.swing.JButton();
        btnLogOut = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MENU");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("MENU");

        btChatBox.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Community Help copy.png"))); // NOI18N
        btChatBox.setText("CHAT AREA");
        btChatBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btChatBoxActionPerformed(evt);
            }
        });

        btGame.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Music8688.png"))); // NOI18N
        btGame.setText("GAME");
        btGame.setPreferredSize(new java.awt.Dimension(90, 60));

        btSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/AQUA ICONS SYSTEM SEARCH copy.png"))); // NOI18N
        btSearch.setText("SEARCH");
        btSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btSearchMouseClicked(evt);
            }
        });

        btMessages.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/! copy.png"))); // NOI18N
        btMessages.setText("MESSAGES");
        btMessages.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btMessagesMouseClicked(evt);
            }
        });

        btRequest.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/close folder copy.png"))); // NOI18N
        btRequest.setText("REQUEST");
        btRequest.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btRequestMouseClicked(evt);
            }
        });

        btInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/AQUA ICONS APPLICATIONS MS MESSENGER copy.png"))); // NOI18N
        btInfo.setText("INFO");
        btInfo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btInfoMouseClicked(evt);
            }
        });

        tfSearch.setToolTipText("name");
        tfSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ontfSearch_type(evt);
            }
        });

        btEnter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/AQUA ICONS SYSTEM SEARCH copy_1.png"))); // NOI18N
        btEnter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEnterActionPerformed(evt);
            }
        });

        add.setText("+");
        add.setToolTipText("add friend");
        add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addActionPerformed(evt);
            }
        });

        btnLogOut.setText("Log Out");
        btnLogOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLogOutActionPerformed(evt);
            }
        });
        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btChatBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
                    .addComponent(btGame, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btMessages, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btInfo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btRequest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btEnter)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(add)))
                .addGap(32, 32, 32))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnLogOut)
                .addGap(41, 41, 41))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btChatBox, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btGame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btMessages, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btRequest, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btEnter, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addComponent(btnLogOut)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSearchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btSearchMouseClicked
        
    }//GEN-LAST:event_btSearchMouseClicked

    private void btMessagesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btMessagesMouseClicked
        ClientModel.getInstance().getForms().showChatForm("0", ClientForms.CHATFORM_WORLD);
    }//GEN-LAST:event_btMessagesMouseClicked

    private void btRequestMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btRequestMouseClicked
        ClientModel.getInstance().getForms().getFriendRequest().setVisible(true);
    }//GEN-LAST:event_btRequestMouseClicked

    private void btInfoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btInfoMouseClicked
        ClientModel.getInstance().getForms().getUserInfo().setVisible(true);
    }//GEN-LAST:event_btInfoMouseClicked

    
    private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
        try 
        {
            int selectedIndex = friendList.getSelectedIndex();
            if (selectedIndex < 0 || this.isFriendList.get(selectedIndex))
            {
                return;
            }
            
            Account friendAcc = (Account) this.userModel.getElementAt(selectedIndex);
            final menu copyThis = this;
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "sendRequestFriend")
                    .set("Name", ClientModel.getInstance().getAccount().getUserID())
                    .set("FriendName", friendAcc.getUserID());
            QClient.getInstance().getRequestManager().sendRequest(
                    new Request("Relation", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    boolean isSuccess = respond.getBoolean(RequestParameters.KEY_RESULT);
                    if (isSuccess)
                    {
                        JOptionPane.showMessageDialog(copyThis, "Friend request added");
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(copyThis, "We were friend ^^");
                    }
                }
            }));
        } catch (IOException ex) 
        {
            Logger.getLogger(menu.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_addActionPerformed

    private void btEnterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEnterActionPerformed
        search(true, '\n');
    }//GEN-LAST:event_btEnterActionPerformed

    private void ontfSearch_type(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ontfSearch_type
    
    }//GEN-LAST:event_ontfSearch_type

    private void btChatBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btChatBoxActionPerformed
        ClientModel.getInstance().getForms().showChatForm("0", ClientForms.CHATFORM_WORLD);
    }//GEN-LAST:event_btChatBoxActionPerformed

    private void btnLogOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogOutActionPerformed
        ClientModel.clear();
        ClientModel.getInstance().getForms().getLoginForm().setVisible(true);
    }//GEN-LAST:event_btnLogOutActionPerformed

    private boolean search(boolean isButtonPressed, char key)
    {
        String senderID   =   ClientModel.getInstance().getAccount().getUserID();
        String searchString  = this.tfSearch.getText();
        try 
        {
            RequestParameters params = new RequestParameters()
                                            .set(RequestParameters.KEY_FUNCTION, "searchUsers")
                                            .set("SenderID", senderID)
                                            .set("SearchString", searchString);
            final menu copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(
                    new Request("Querry", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    copyThis.isFriendList.clear();
                    copyThis.userModel.clear();
                    if (respond.isSuccess())
                    {
                        copyThis.userModel.getFullAccounts().clear();
                        copyThis.userModel.addAccounts((ArrayList<Account>)respond.getResult());
                        copyThis.isFriendList.addAll((ArrayList<Boolean>)respond.get("IsFriend"));
                    }
                }
            }));
        } catch (IOException ex)
        {
            Logger.getLogger(loginForm.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex);
        }
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton add;
    private javax.swing.JButton btChatBox;
    private javax.swing.JButton btEnter;
    private javax.swing.JButton btGame;
    private javax.swing.JButton btInfo;
    private javax.swing.JButton btMessages;
    private javax.swing.JButton btRequest;
    private javax.swing.JButton btSearch;
    private javax.swing.JButton btnLogOut;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JTextField tfSearch;
    // End of variables declaration//GEN-END:variables
    private javax.swing.JList friendList;
    private javax.swing.JScrollPane scrollPaneFriendlist;
}
